package com.example.datamaskingdemo.filter;

import com.alibaba.fastjson.serializer.ValueFilter;
import com.example.datamaskingdemo.annotation.Desensitized;
import com.example.datamaskingdemo.enumType.SensitiveTypeEnum;
import com.example.datamaskingdemo.utils.DesensitizedUtils;

import java.lang.reflect.Field;

public class ValueDesensitizeFilter implements ValueFilter {
    @Override
    public Object process(Object object, String name, Object value) {
        if (null == value || !(value instanceof String) || ((String) value).length() == 0) {
            return value;
        }
        try {
            Field field = object.getClass().getDeclaredField(name);
            Desensitized desensitization;
            if (String.class != field.getType() || (desensitization = field.getAnnotation(Desensitized.class)) == null) {
                return value;
            }
            String valueStr = (String) value;
            SensitiveTypeEnum type = desensitization.type();
            switch (type) {
                case TELEPHONE:
                    return DesensitizedUtils.telephone(valueStr);
            }
        }catch (NoSuchFieldException e){
            return value;
        }
        return value;
    }
}